package com.om39a.plm.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.om39a.plm.utils.PLMUtils;

/**
 * @author om39a
 * 
 */
public class ParserThreadUrl extends PLMParser {

	static Logger logger = Logger.getLogger(ParserThreadUrl.class);

	public void parse(String content, List<PLMThreadPost> plmThreadPosts) {
		logger.info("Entring into parse - content - " + plmThreadPosts);
		// ThreadData threadData;
		PLMThreadPost plmThreadPost;
		Document doc = Jsoup.parse(content);
		Elements threadDate = doc.select("div[class=thread-date]");
		// Selecting Thread ID for the thread

		String threadId = getThreadID(threadDate);
		// Selecting tags for the thread
		Elements tagElements = doc
				.getElementsByAttributeValue("class", "topic");
		List<String> tags = new ArrayList<String>();
		for (Element element : tagElements) {
			tags.add(element.text());
		}
		for (Element threadDateElement : threadDate) {

			try {

				// Thread new_thread = new Thread();
				plmThreadPost = new PLMThreadPost();
				// Set thread id to thread object
				plmThreadPost.setThreadId(threadId);
				// Set parent forum name
				plmThreadPost.setParentForum(getForumTitle(doc));
				plmThreadPost.setThreadtags(tags);
				Elements forumTagsHeader = doc.getElementsByAttributeValue(
						"class", "tags-header");
				// set thread title
				plmThreadPost.setThreadTitle(getThreadTitle(forumTagsHeader));
				// Thread created by user name
				plmThreadPost
						.setThreadCreatedBy(getCreatedByUserName(forumTagsHeader));
				// Thread created date
				plmThreadPost
						.setThreadCreatedDate(getThreadCreatedDate(forumTagsHeader));

				Elements postName = threadDateElement
						.getElementsByAttribute("name");
				// Getting the post id
				plmThreadPost.setPostId(getPostName(postName));
				// Getting the post creation time
				// Collection post id and posted time
				plmThreadPost.setPostCreatedDate(getPostCreationDate(postName));
				// finding posts based on the post Id form previous step and
				// collection post contents
				Element threadPost = doc.getElementById("post-"
						+ getPostName(postName));
				getUserDetails(plmThreadPost, threadPost);
				getPostContents(plmThreadPost, threadPost);
				getHelpfullMarkers(plmThreadPost, threadPost);
				plmThreadPosts.add(plmThreadPost);
			} catch (Exception e) {
				e.printStackTrace();
				logger.info(e);
			}
		}
		logger.info("Exiting from parse");
	}

	private void getUserDetails(PLMThreadPost plmThreadPost, Element threadPost) {
		// Post Create by is added to the post

		// <!---- this logic wil be used while parsing user details --!>
		// Checking the thread Sig for the user role. Based on the user
		// role, extracting the corresponding text
		Elements threadSig = threadPost.getElementsByAttributeValue("class",
				"thread-sig");

		if (threadSig.text().contains("Moderator")
				|| threadSig.text().contains("Admin")
				|| threadSig.text().contains("Plm-researcher")
				|| threadSig.text().contains("Alumni")) {
			plmThreadPost.setPostCreatedBy(threadSig.select("span").first()
					.text());
			plmThreadPost.setPostUserProfileUrl(threadSig.select(
					"a[href],[class=nugget-link]").attr("href"));
		} else if (threadSig.text().contains("PLM Alum")) {
			plmThreadPost.setPostCreatedBy(threadSig.select("span").first()
					.text());
			plmThreadPost.setPostUserProfileUrl(threadSig.select(
					"a[href],[class=nugget-link]").attr("href"));
		} else if (threadSig.text().contains("Deactivated")) {
			plmThreadPost.setPostCreatedBy(threadSig.select("span").first()
					.text());
			plmThreadPost.setPostUserProfileUrl(threadSig.select(
					"a[href],[class=nugget-link]").attr("href"));
		} else {
			plmThreadPost.setPostCreatedBy(threadPost
					.getElementsByAttributeValueContaining("href",
							"/patients/view/").first().text());
			plmThreadPost.setPostUserProfileUrl(threadSig.select(
					"a[href],[class=nugget-link]").attr("href"));
		}
	}

	private void getHelpfullMarkers(PLMThreadPost plmThreadPost,
			Element threadPost) {
		// Selecting helpful markers
		Elements sectHelpful = threadPost.getElementsByAttributeValue("class",
				"sect-helpful");
		if (!"Mark this post as helpful"
				.equalsIgnoreCase(getPostCreationDate(sectHelpful))) {
			plmThreadPost.setPostHelpFullMarks(getPostCreationDate(sectHelpful)
					.replaceAll("\\D", ""));
		} else {
			plmThreadPost.setPostHelpFullMarks("0");
		}
	}

	private void getPostContents(PLMThreadPost plmThreadPost, Element threadPost) {
		Elements mainContent = threadPost.getElementsByAttributeValue("class",
				"text");

		// Select main post content
		plmThreadPost.setPostContent(mainContent.text());

		List<String> treatmentUrlsList = new ArrayList<String>();
		List<String> otherContentUrlsList = new ArrayList<String>();

		// Select URL's in the content
		Elements treatmentUrls = mainContent
				.select("a[href][class=treatment-link]");
		for (Element element : treatmentUrls) {
			treatmentUrlsList.add(PLMUtils.appendBaseURL(element.attr("href")));
			element.remove();
		}
		Elements contentUrls = mainContent.select("a[href]");
		for (Element element : contentUrls) {
			otherContentUrlsList.add(element.attr("href"));
			element.remove();
		}

		// Set treatment and content urls
		plmThreadPost.setTreatmentUrls(treatmentUrlsList);
		plmThreadPost.setContentUrls(otherContentUrlsList);
	}

	private String getPostCreationDate(Elements postName) {
		return postName.text();
	}

	private String getPostName(Elements postName) {
		return postName.attr("name");
	}

	private String getThreadCreatedDate(Elements forumTagsHeader) {
		return forumTagsHeader.select("span[class=create-date]").first().text();
	}

	private String getCreatedByUserName(Elements forumTagsHeader) {
		String postedByUserName;
		if (forumTagsHeader.select("a[href*=/patients/view/]") != null
				&& forumTagsHeader.select("a[href*=/patients/view/]").size() != 0) {
			postedByUserName = forumTagsHeader
					.select("a[href*=/patients/view/]").first().text();
		} else if (forumTagsHeader.select("a[href*=/members/view/]") != null
				&& forumTagsHeader.select("a[href*=/members/view/]").size() != 0) {
			postedByUserName = forumTagsHeader
					.select("a[href*=/members/view/]").first().text();
		} else {
			postedByUserName = forumTagsHeader.select("span").first().text();
		}
		return postedByUserName;
	}

	private String getThreadTitle(Elements forumTagsHeader) {
		String threadTitle = forumTagsHeader.select("h2").first().text();
		return threadTitle;
	}

	private String getForumTitle(Document doc) {
		// Selecting parent forum title
		Elements forumTitle = doc.getElementsByAttributeValue("class",
				"section-intro");
		String parentForum = forumTitle.select("h1").text();
		return parentForum;
	}

	private String getThreadID(Elements threadDate) {
		Elements threadUrl = threadDate.select("a");
		String url = threadUrl.attr("href");
		Pattern pattern = Pattern.compile("/forum/\\w+/topics/(\\d+)\\?");
		Matcher matcher = pattern.matcher(url);
		String threadId = "NA";
		if (matcher.find()) {
			threadId = matcher.group(1);
		}
		return threadId;
	}

}
